package cn.fiveinone;

import cn.fiveinone.setting.Setting;
import sun.security.provider.NativePRNG;

import java.util.concurrent.*;

/**
 * @Description
 * @auther Szper
 * @create 2019-10-24 14:12
 */
public class PoolExactor {
    public static ThreadPoolExecutor tpe = null;
    public static ScheduledThreadPoolExecutor stpe = null;
    static synchronized ThreadPoolExecutor tpe () {
        if (tpe == null) {
            int corePoolSize = Setting.getCorePoolSize();
            int maximumPoolSize = Setting.getMaximumPoolSize();
            long  keepAliveTime = Setting.getKeepAliveTime();
            TimeUnit unit = TimeUnit.MILLISECONDS;
            BlockingQueue<Runnable> waitQueue = new ArrayBlockingQueue<Runnable>(2000);
            RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
            tpe = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, waitQueue, handler);
        }
        return tpe;
    }
    static ScheduledThreadPoolExecutor stpe()
    {
        if(stpe==null)
        {
            int corePoolSize = Setting.getCorePoolSize();
            stpe =new ScheduledThreadPoolExecutor(corePoolSize);
        }
        return stpe;
    }

    static void execute(Runnable d, Runnable i, long t){
        tpe().execute(d);
        if(t>0)
            stpe().schedule(i,t,TimeUnit.SECONDS);
    }

    static synchronized void close(){//
        if(tpe!=null){
            try{
                //System.out.println(Thread.currentThread()+":shutdown ThreadPoolExecutor...");
                while(tpe.getActiveCount()!=0);//2015.8.13
                tpe.shutdown();
                //tpe.awaitTermination(1, TimeUnit.DAYS);
                tpe=null;
            }catch(SecurityException se){
                System.out.println("[tpe]"+"[close]"+"[Error Exception:]"+se);
            }
        }
        if(stpe!=null){
            try{
                stpe.shutdown();
                stpe=null;
            }catch(SecurityException se){
                System.out.println("[stpe]" + "[close]" + "[Error Exception:]" + se);
            }
        }
    }
}
